package com.hlj.ncp.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hlj.ncp.common.core.domain.AjaxResult;
import com.hlj.ncp.system.entity.SysUser;
import com.hlj.ncp.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户信息操作处理
 */
@Controller
@RequestMapping("/system/user")
public class UserController {

    @Autowired
    private SysUserMapper userMapper;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    /**
     * 用户管理页面
     */
    @GetMapping({"", "/", "/index"})
    public String index() {
        return "system/user/index";
    }

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/info")
    @ResponseBody
    public AjaxResult getUserInfo() {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        
        // 查询用户详细信息
        SysUser user = null;
        
        // 如果不是匿名用户，则查询数据库
        if (!"anonymousUser".equals(username)) {
            LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysUser::getUsername, username);
            user = userMapper.selectOne(wrapper);
        }
        
        // 如果未找到用户但用户名是admin（演示环境），创建默认admin用户
        if (user == null && "admin".equals(username)) {
            user = new SysUser();
            user.setUserId(1L);
            user.setUsername("admin");
            user.setNickName("管理员");
            user.setEmail("admin@example.com");
            user.setPhone("13800138000");
            user.setSex("0");
            user.setAvatar("/profile/avatar/default.jpg");
            user.setStatus("0");
        }
        
        // 如果仍未找到用户，可能是匿名用户或其他问题
        if (user == null) {
            return AjaxResult.error("未找到用户信息");
        }
        
        // 构建返回结果，过滤掉敏感信息
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("userId", user.getUserId());
        userInfo.put("username", user.getUsername());
        userInfo.put("nickName", user.getNickName());
        userInfo.put("email", user.getEmail());
        userInfo.put("phone", user.getPhone());
        userInfo.put("sex", user.getSex());
        userInfo.put("avatar", user.getAvatar());
        userInfo.put("status", user.getStatus());
        userInfo.put("createTime", user.getCreateTime());
        
        // 设置权限信息
        userInfo.put("roles", authentication.getAuthorities());
        
        return AjaxResult.success(userInfo);
    }
    
    /**
     * 获取用户列表
     */
    @PostMapping("/list")
    @ResponseBody
    @Cacheable(value = "userList", key = "#params.toString()", unless = "#result.get('code') != 200")
    @Transactional(readOnly = true)
    public AjaxResult list(@RequestBody Map<String, Object> params) {
        Integer pageNum = (Integer) params.getOrDefault("pageNum", 1);
        Integer pageSize = (Integer) params.getOrDefault("pageSize", 10);
        String username = (String) params.get("username");
        String nickName = (String) params.get("nickName");
        String status = (String) params.get("status");
        
        // 构建查询条件
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getDelFlag, "0");
        
        if (StringUtils.hasText(username)) {
            queryWrapper.like(SysUser::getUsername, username);
        }
        if (StringUtils.hasText(nickName)) {
            queryWrapper.like(SysUser::getNickName, nickName);
        }
        if (StringUtils.hasText(status)) {
            queryWrapper.eq(SysUser::getStatus, status);
        }
        
        // 排序
        queryWrapper.orderByDesc(SysUser::getCreateTime);
        
        // 分页查询
        Page<SysUser> page = new Page<>(pageNum, pageSize);
        Page<SysUser> userPage = userMapper.selectPage(page, queryWrapper);
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("total", userPage.getTotal());
        result.put("rows", userPage.getRecords());
        
        return AjaxResult.success(result);
    }
    
    /**
     * 新增用户
     */
    @PostMapping("/add")
    @ResponseBody
    @CacheEvict(value = "userList", allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@RequestBody SysUser user) {
        // 验证用户名是否已存在
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, user.getUsername())
                   .eq(SysUser::getDelFlag, "0");
        
        if (userMapper.selectCount(queryWrapper) > 0) {
            return AjaxResult.error("用户名已存在");
        }
        
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        
        // 设置默认值
        user.setDelFlag("0");
        user.setCreateTime(LocalDateTime.now());
        user.setCreateBy(getCurrentUsername());
        
        // 插入数据
        int rows = userMapper.insert(user);
        return rows > 0 ? AjaxResult.success() : AjaxResult.error("新增用户失败");
    }
    
    /**
     * 修改用户
     */
    @PostMapping("/update")
    @ResponseBody
    @CacheEvict(value = "userList", allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult update(@RequestBody SysUser user) {
        // 验证用户是否存在
        SysUser existUser = userMapper.selectById(user.getUserId());
        if (existUser == null) {
            return AjaxResult.error("用户不存在");
        }
        
        // 如果修改了用户名，需要验证用户名是否已存在
        if (!existUser.getUsername().equals(user.getUsername())) {
            LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUser::getUsername, user.getUsername())
                       .eq(SysUser::getDelFlag, "0");
            
            if (userMapper.selectCount(queryWrapper) > 0) {
                return AjaxResult.error("用户名已存在");
            }
        }
        
        // 不更新密码
        user.setPassword(null);
        
        // 设置更新信息
        user.setUpdateTime(LocalDateTime.now());
        user.setUpdateBy(getCurrentUsername());
        
        // 更新数据
        int rows = userMapper.updateById(user);
        return rows > 0 ? AjaxResult.success() : AjaxResult.error("修改用户失败");
    }
    
    /**
     * 删除用户
     */
    @PostMapping("/delete")
    @ResponseBody
    @CacheEvict(value = "userList", allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult delete(@RequestBody Map<String, Object> params) {
        Long userId = Long.valueOf(params.get("userId").toString());
        
        // 验证用户是否存在
        SysUser user = userMapper.selectById(userId);
        if (user == null) {
            return AjaxResult.error("用户不存在");
        }
        
        // 不允许删除超级管理员
        if ("admin".equals(user.getUsername())) {
            return AjaxResult.error("不允许删除超级管理员");
        }
        
        // 逻辑删除
        user.setDelFlag("1");
        user.setUpdateTime(LocalDateTime.now());
        user.setUpdateBy(getCurrentUsername());
        
        int rows = userMapper.updateById(user);
        return rows > 0 ? AjaxResult.success() : AjaxResult.error("删除用户失败");
    }
    
    /**
     * 导出用户
     */
    @GetMapping("/export")
    @ResponseBody
    @Transactional(readOnly = true)
    public AjaxResult export(String username, String nickName, String status) {
        // 构建查询条件
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getDelFlag, "0");
        
        if (StringUtils.hasText(username)) {
            queryWrapper.like(SysUser::getUsername, username);
        }
        if (StringUtils.hasText(nickName)) {
            queryWrapper.like(SysUser::getNickName, nickName);
        }
        if (StringUtils.hasText(status)) {
            queryWrapper.eq(SysUser::getStatus, status);
        }
        
        // 查询所有符合条件的用户
        List<SysUser> userList = userMapper.selectList(queryWrapper);
        
        // 实际项目中应该生成Excel文件并提供下载
        // 这里简化处理，直接返回用户列表
        return AjaxResult.success(userList);
    }
    
    /**
     * 获取当前登录用户名
     */
    private String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication.getName();
    }
} 